﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using LimpaGaragem.BLL;
using LimpaGaragem.Model;

namespace LimpaGaragem.Web.Pages.Users
{
    public partial class Register : System.Web.UI.Page
    {

        #region VARIABLES

        #endregion

        #region EVENTS

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadStates();
            }
        }

        protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlState.SelectedIndex != -1)
            {
                LoadCities(Convert.ToInt32(ddlState.SelectedItem.Value));
            }
        }

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            RegisterUser();
        }

        #endregion

        #region METHODS

        private void LoadStates()
        {
            try
            {
                ddlState.DataTextField = "Acronym";
                ddlState.DataValueField = "ID";
                ddlState.DataSource = new BLL.Generic.State().GetListOfState();
                ddlState.DataBind();
                upRegister.Update();
            }
            catch (Exception ex)
            {
                //ERRO
            }
        }

        private void LoadCities(int IDState)
        {
            try
            {
                ddlCity.DataTextField = "Name";
                ddlCity.DataValueField = "ID";
                ddlCity.DataSource = new BLL.Generic.City().GetListOfCity(IDState);
                ddlCity.DataBind();
                upRegister.Update();
            }
            catch (Exception ex)
            {
                //ERRO
            }
        }

        private bool ValidateRegister()
        {
            try
            {
                //VARIABLE
                bool valid = true;
                string message = string.Empty;

                //VALIDATIONS
                //LOGIN
                if (txtLoginUser.Text.Trim() == string.Empty)
                {
                    valid = false;
                    message = "Nome do usuário não preenchido!\\n";
                }
                //PASSWORD
                if (txtPwUser.Text.Trim() == string.Empty)
                {
                    valid = false;
                    message += "Senha do usuário não preenchida!\\n";
                }
                //NAME
                if (txtName.Text.Trim() == string.Empty)
                {
                    valid = false;
                    message += "Nome não preenchido!\\n";
                }
                //DATE
                if (txtBirthDate.Text.Trim() == string.Empty)
                {
                    valid = false;
                    message += "Data de nascimento não preenchida!\\n";
                }
                else
                {
                    DateTime tryConvertToDate;
                    if (!DateTime.TryParse(txtBirthDate.Text, out tryConvertToDate))
                    {
                        valid = false;
                        message += "Data de nascimento inválida!\\n";
                    }
                }
                //EMAIL
                if (txtEmail.Text.Trim() == string.Empty)
                {
                    valid = false;
                    message += "E-mail não preenchido!\\n";
                }
                else
                {
                    if (!ValidateEmail(txtEmail.Text))
                    {
                        valid = false;
                        message += "E-mail inválido!\\n";
                    }
                }
              
                //CPF
                if (txtCPF.Text.Trim() == string.Empty)
                {
                    valid = false;
                    message += "CPF não preenchido!\\n";
                }
                else
                {
                    if (!ValidateCPF(txtCPF.Text))
                    {
                        valid = false;
                        message += "CPF inválido!\\n";
                    }
                }

                //SHOW ALERT MESSAGE
                if (message != string.Empty)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "window.alert(\"" + message + "\");",true);                   
                }
                //RETURN RESULT
                return valid;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void RegisterUser()
        {
            try
            {
                if (ValidateRegister())
                {
                    //INSTANCE INFO
                    BLL.User.Info objInfo = new BLL.User.Info();

                    //GET VALUES
                    string strLogin = txtLoginUser.Text.Trim();
                    string strPassword = txtPwUser.Text.Trim();
                    string strName = txtName.Text.Trim();
                    DateTime dtBirthday = Convert.ToDateTime(txtBirthDate.Text);
                    string strEmail = txtEmail.Text.Trim();
                    decimal decCPF = Convert.ToDecimal(txtCPF.Text.Trim().Replace(".", "").Replace("-", ""));
                    string strPhone = txtPhone.Text.Trim();
                    string strCellPhone = txtCellPhone.Text.Trim();
                    string strAdress = txtAdress.Text.Trim();
                    int? intAdressNumber = null;
                    if (txtAdressNumber.Text.Trim() != string.Empty)
                        intAdressNumber = Convert.ToInt32(txtAdressNumber.Text.Trim());
                    string strAdditionalAdress = txtAdditAdress.Text.Trim();
                    decimal? decCEP = null;
                    if (txtPostalCode.Text.Trim() != string.Empty)
                        decCEP = Convert.ToDecimal(txtPostalCode.Text.Trim().Replace("-", ""));
                    int? intIDCity = null;
                    if (ddlCity.SelectedIndex != -1)
                        intIDCity = Convert.ToInt32(ddlCity.SelectedItem.Value);
                    bool blShowContactInfo = chkShowContactInfo.Checked;

                    //INSERT USER
                    int IDUser = objInfo.InsertUser(strLogin,
                                                    strName,
                                                    strEmail,
                                                    strPassword,
                                                    dtBirthday,
                                                    decCPF,
                                                    strAdress,
                                                    intAdressNumber,
                                                    strAdditionalAdress,
                                                    decCEP,
                                                    intIDCity,
                                                    strPhone,
                                                    strCellPhone,
                                                    blShowContactInfo);
                    if (IDUser > 0)
                    {
                        objInfo.SendConfirmationEmail(strEmail,IDUser,strLogin,strPassword,strName);
                        ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "window.alert(\"Seu usuário foi cadastrado!\\n\\nVerifique e confirme o e-mail enviado para confirmação do cadastro!\");", true);                   
                    }
                    else
                        ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "window.alert(\"Desculpe o transtorno!\\n\\nOcorreu algum erro em nosso sistema e não foi possível realizar o cadastro!\");", true);                   
                }
            }
            catch (Exception ex)
            {
                //ERRO
            }
        }

        #region Validate Methods

        private bool ValidateEmail(string email)
        {
            bool validEmail = false;
            int indexArr = email.IndexOf('@');
            if (indexArr > 0)
            {
                int indexDot = email.IndexOf('.', indexArr);
                if (indexDot - 1 > indexArr)
                {
                    if (indexDot + 1 < email.Length)
                    {
                        string indexDot2 = email.Substring(indexDot + 1, 1);
                        if (indexDot2 != ".")
                        {
                            validEmail = true;
                        }
                    }
                }
            }
            return validEmail;
        }

        public bool ValidateCPF(string cpf)
        {



            int[] multiplicador1 = new int[9] { 10, 9, 8, 7, 6, 5, 4, 3, 2 };

            int[] multiplicador2 = new int[10] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };



            string tempCpf;

            string digito = "";

            int soma;

            int endfile = 0;



            cpf = cpf.Trim();

            cpf = cpf.Replace(".", "").Replace("-", "");



            if ((cpf.Length != 11) || (cpf == 00000000000.ToString()) || (cpf == 11111111111.ToString()) || (cpf == 22222222222.ToString()) || (cpf == 33333333333.ToString()) || (cpf == 44444444444.ToString()) || (cpf == 55555555555.ToString()) || (cpf == 66666666666.ToString()) || (cpf == 77777777777.ToString()) || (cpf == 88888888888.ToString()) || (cpf == 99999999999.ToString()))
            {



                return false;

            }



            // tempCpf está recebendo os caracteres da posição 0 até a posição 9

            tempCpf = cpf.Substring(0, 9);

            soma = 0;



            for (int i = 0; i < 9; i++)
            {

                soma = soma + Convert.ToInt32(tempCpf.Substring(i, 1)) * multiplicador1[i];

                endfile = soma % 11;

            }



            if (endfile < 2)
            {

                endfile = 0;

            }



            else
            {

                endfile = 11 - endfile;

                digito = endfile.ToString();

                tempCpf = tempCpf + digito;

                soma = 0;

            }



            for (int i = 0; i < 10; i++)
            {

                soma = soma + Convert.ToInt32(tempCpf.Substring(i, 1)) * multiplicador2[i];

                endfile = soma % 11;

            }



            if (endfile < 2)

                endfile = 0;



            else
            {

                endfile = 11 - endfile;

                digito = digito + endfile.ToString();

            }



            return true;



        }

        #endregion

        #endregion
    }
}